<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择工单状态" clearable style="width: 100px;">
          <el-option
            v-for="dict in task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建类型" prop="createType">
        <el-select v-model="queryParams.createType" placeholder="请选择创建类型" clearable style="width: 100px;">
          <el-option
            v-for="dict in task_create_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型" prop="taskTypeId" >
        <el-select
          v-model="queryParams.taskTypeId"
          placeholder="请输入工单类型"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        >
          <el-option v-for="item in taskTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="充电桩编码" prop="pileSn">
        <el-input
          v-model="queryParams.pileSn"
          placeholder="请输入充电桩编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属区域ID" prop="regionId">
        <el-input
          v-model="queryParams.regionId"
          placeholder="请输入所属区域ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行人ID" prop="empId">
        <el-input
          v-model="queryParams.empId"
          placeholder="请输入执行人ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行人名称 " prop="empName">
        <el-input
          v-model="queryParams.empName"
          placeholder="请输入执行人名称 "
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人/指派人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人/指派人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="工单编号" align="center" prop="taskCode" />

      <!-- <el-table-column label="创建类型" align="center" prop="createType">
        <template #default="scope">
          <dict-tag :options="task_create_type" :value="scope.row.createType"/>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="工单类型" align="center" prop="taskTypeId" >
        <template #default="scope">
          <div v-for="item in taskTypeList">
            <span v-if="item.id === scope.row.taskTypeId">{{ item.typeName }}</span>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="设备编码" align="center" prop="pileSn" />
      <!-- <el-table-column label="详细地址" align="center" prop="addr" /> -->
      <!-- <el-table-column label="所属区域ID" align="center" prop="regionId" />
      <!-- <el-table-column label="执行人ID" align="center" prop="empId" /> --> -->
      <el-table-column label="执行人名称 " align="center" prop="empName" />
      <el-table-column label="工单状态" align="center" prop="taskStatus">
        <template #default="scope">
          <dict-tag :options="task_status" :value="scope.row.taskStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="工单描述" align="center" prop="taskDesc" />
      <el-table-column label="完成时间" align="center" prop="finishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['manage:task:query']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:task:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单类型" prop="taskTypeId">
          <el-select v-model="form.taskTypeId" placeholder="请输入选择工单类型" >
            <el-option v-for="item in taskTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" prop="regionId" >
          <el-select v-model="form.regionId" placeholder="请输入所属区域" @change="getPileList(form.regionId)">
            <el-option v-for="item in regionList" :key="item.id" :label="item.regionName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.regionId !== null && form.regionId !== ''" label="设备编码" prop="pileSn">
          <el-select v-model="form.pileSn" placeholder="请输入充电桩编码" >
            <el-option
              v-for="item in pileList"
              :key="item.pileSn"
              :label="item.pileName"
              :value="item.pileSn"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.regionId !== null && form.regionId !== ''" label="执行人员 " prop="empName">
          <el-select v-model="form.empName" placeholder="请输入执行人名称 " >
            <el-option v-for="item in empList" :key="item.id" :label="item.userName" :value="item.userName" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.regionId !== null && form.regionId !== ''" label="执行人id" prop="empId">
          <div v-for="item in empList">
            <span v-if="item.userName === form.empName">{{ item.id }}</span>
          </div>
        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="工单描述" prop="taskDesc">
          <el-input v-model="form.taskDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工单详情对话框 -->
    <el-dialog title="工单详情" v-model="detailOpen" width="600px" append-to-body>
      <div v-if="detailForm && Object.keys(detailForm).length > 0">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">{{ detailForm.taskCode || '-' }}</el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <dict-tag :options="task_status" :value="detailForm.taskStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label="工单类型">
            <span v-for="item in taskTypeList" :key="item.id">
              <span v-if="item.id === detailForm.taskTypeId">{{ item.typeName }}</span>
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="创建类型">
            <dict-tag :options="task_create_type" :value="detailForm.createType"/>
          </el-descriptions-item>
          <el-descriptions-item label="所属区域">
            <span v-for="item in regionList" :key="item.id">
              <span v-if="item.id === detailForm.regionId">{{ item.regionName }}</span>
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="设备编码">{{ detailForm.pileSn || '-' }}</el-descriptions-item>
          <el-descriptions-item label="执行人">{{ detailForm.empName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">{{ detailForm.addr || '-' }}</el-descriptions-item>
          <el-descriptions-item label="工单描述" :span="2">{{ detailForm.taskDesc || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            <span>{{ detailForm.createTime ? parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="完成时间">
            <span>{{ detailForm.finishTime ? parseTime(detailForm.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detailForm.createBy || '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">
            <span>{{ detailForm.updateTime ? parseTime(detailForm.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else>
        <p>加载中...</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <!-- 待办状态显示取消工单按钮 -->
          <el-button 
            v-if="detailForm.taskStatus == 1 || detailForm.taskStatus == 2" 
            type="danger" 
            @click="handleCancelTask"
          >取消工单</el-button>
          <!-- 已取消状态显示重新创建按钮 -->
          <el-button 
            v-if="detailForm && detailForm.taskStatus === 3" 
            type="primary" 
            @click="handleRecreateTask"
          >重新创建</el-button>
          <el-button @click="closeDetailDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask, cancelTask } from "@/api/manage/task"
import { listTaskType } from "@/api/manage/taskType"
import { listRegion } from "@/api/manage/region"
import { loadAllParams } from "@/api/page"
import { listPile } from "@/api/manage/pile"
import { listEmp } from "@/api/manage/emp"
const { proxy } = getCurrentInstance()
const { task_status, task_create_type } = proxy.useDict('task_status', 'task_create_type')

const taskList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const detailForm = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskCode: null,
    taskStatus: null,
    taskTypeId: null,
    pileSn: null,
    regionId: null,
    empId: null,
    empName: null,
    createBy: null,
  },
  rules: {
    taskStatus: [
      { required: true, message: "工单状态 (0=待派发, 1=待处理, 2=处理中, 3=已完成, 4=已取消)不能为空", trigger: "change" }
    ],
    regionId: [
      { required: true, message: "所属区域不能为空", trigger: "blur" }
    ],
    taskTypeId: [
      { required: true, message: "工单类型不能为空", trigger: "blur" }
    ],
    pileSn: [
      { required: true, message: "充电桩编码不能为空", trigger: "blur" }
    ],
    empId: [
      { required: true, message: "执行人ID不能为空", trigger: "blur" }
    ],
    empName:[
      { required: true, message: "执行人名称不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询工单列表 */
function getList() {
  loading.value = true
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    taskCode: null,
    taskStatus: null,
    taskTypeId: null,
    pileSn: null,
    addr: null,
    regionId: null,
    empId: null,
    empName: null,
    taskDesc: null,
    finishTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("taskRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data
    getPileList(form.value.regionId)
    open.value = true
    title.value = "修改工单"
    
  })
}

/** 查看按钮操作 */
function handleView(row) {
  const _id = row.id
  console.log('查看工单详情，ID:', _id)
  loading.value = true
  getTask(_id).then(response => {
    console.log('获取工单详情成功:', response.data)
    detailForm.value = response.data
    console.log('detailForm.value', detailForm.value)
    detailOpen.value = true
    loading.value = false
  }).catch((error) => {
    console.error('获取工单详情失败:', error)
    loading.value = false
    proxy.$modal.msgError("获取工单详情失败")
  })
}

/** 关闭详情对话框 */
function closeDetailDialog() {
  detailOpen.value = false
  detailForm.value = {}
}

/** 取消工单操作 */
function handleCancelTask() {
  cancelTask(detailForm.value).then(response => {
    detailOpen.value = false
    getList()
    ElMessage.success("取消工单成功")
  }).catch(() => {
    ElMessage.error("取消工单失败")
  })
}

/** 重新创建工单操作 */
function handleRecreateTask() {
  // 关闭详情对话框
  detailOpen.value = false
  // 重置表单
  reset()
  // 将详情数据填入新增表单，但清空一些不应该复制的字段
  form.value = {
    id: null,
    taskCode: null,
    taskStatus: null,
    taskTypeId: detailForm.value.taskTypeId,
    pileSn: detailForm.value.pileSn,
    addr: detailForm.value.addr,
    regionId: detailForm.value.regionId,
    empId: detailForm.value.empId, // 重新选择执行人
    empName: detailForm.value.empName, // 重新选择执行人
    taskDesc: detailForm.value.taskDesc,
    finishTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  // 如果区域ID存在，获取相关的设备和人员列表
  if (form.value.regionId) {
    getPileList(form.value.regionId)
  }
  // 打开新增对话框
  open.value = true
  title.value = "重新创建工单"
}

/** 提交按钮 */
function submitForm() {
  // 如果选择了执行人，获取执行人ID
  if (form.value.empName && empList.value.length > 0) {
    const emp = empList.value.find(item => item.userName === form.value.empName)
    if (emp) {
      form.value.empId = emp.id
    }
  }

  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("修改失败")
        })
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除工单编号为"' + _ids + '"的数据项？').then(function() {
    return delTask(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

/** 获取工单类型 */
const taskTypeList = ref([])

function getTaskType() {
  listTaskType(loadAllParams.value).then(response => {
    console.log(response)
    taskTypeList.value = response.rows
  })
}

/** 查询区域列表 */ 
const regionList = ref([])
function getRegionList() {
  listRegion(loadAllParams.value).then(response => {
    regionList.value = response.rows;
  })
}

/** 查询点位下所有设备信息 */
const pileList = ref([])
const empList = ref([])

function getPileList(regionId){

  loadAllParams.regionId = regionId
  listPile(loadAllParams).then(response => {
    pileList.value = response.rows
  })
  /** 获取执行人员 */
  listEmp(loadAllParams).then(response => {
    empList.value = response.rows
  })
}

getRegionList()
getTaskType()
getList()
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions-item__label {
  font-weight: bold;
  color: #606266;
}
</style>
